from flask import Blueprint, current_app, request
from flask_json import as_json

from app.models import CommonResult
from . import service
from app import limiter

log = current_app.logger
blog = Blueprint('blog', __name__, url_prefix='/blog')


# 注册蓝图
def register_controller(app):
    app.register_blueprint(blog)


# 分类列表
@blog.get('/category/list')
@as_json
@limiter.limit('10/1 second')
def category_list():
    list = service.category_list()
    return CommonResult(data=list)


# 文章标签
@blog.get('/tag/list')
@as_json
@limiter.limit('10/1 second')
def tag_list():
    date_list = service.tag_list()
    return CommonResult(data=date_list)


# 文章发布日期列表
@blog.post('/article/date_group')
@as_json
@limiter.limit('10/1 second')
def article_date_group():
    data = request.get_json()
    # 如果传入分类id，就查询指定分类的记录
    category_id = data.get('category_id')
    date_list = service.article_date_group(category_id)
    return CommonResult(data=date_list)


# 文章分页
@blog.post('/article/page')
@as_json
@limiter.limit('5/1 second')
def article_page():
    data = request.get_json()
    if not data:
        return CommonResult(code=500, msg='请传入参数')
    # 读取传递的参数
    current = data.get('current')
    page_size = data.get('page_size')
    category_id = data.get('category_id')
    title = data.get('title')
    date = data.get('date')
    common_page = service.article_page(
        category_id, title=title, date=date,
        current=current, page_size=page_size
    )
    return CommonResult(data=common_page)


# 文章按照标签显示
@blog.post('/article/tag')
@as_json
@limiter.limit('5/1 second')
def article_tag():
    data = request.get_json()
    tag_id = data.get('tag_id')
    date_list = service.article_tag(tag_id)
    return CommonResult(data=date_list)


# 查询文章详情
@blog.get('/article/detail/<int:article_id>')
@as_json
@limiter.limit('1/1 second')
def article_detail(article_id):
    article_data = service.article_detail(article_id)
    if article_data is None:
        return CommonResult(code=500, msg='文章不存在')
    else:
        return CommonResult(data=article_data)
